<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\cache\driver\Redis;
use think\Exception;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{
    
    /**
     * Shop模型对象
     * @var \app\admin\model\wanlshop\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Shop;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $redis = (new Redis(config('queue')))->handler();
        $count = $redis->llen('queues:gfjj');
//        $count = 0;
        $this->assignconfig('redislist',$count);
        $this->view->assign('redislist',$count);
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
    
            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
    
            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username']);
            }

            $redis = (new Redis(config('queue')))->handler();
            $count = $redis->llen('queues:gfjj');
//            $count = 0;
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list, "extend" => ['count' => $count]);
    
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 导入
     */
    public function import()
    {
        set_time_limit(0);
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fieldArr = [
            '店铺类型:0=个人,1=企业,2=旗舰' => 'state',
            '店铺名称' => 'shopname',
            '企业名/姓名' => 'name',
            '统一信用/身份证号' => 'number',
            '手机号' => 'mobile',
            '证件图片' => 'image',
            '商标证书' => 'trademark',
            '微信号' => 'wechat',
            '店铺头像' => 'avatar',
            '店铺简介' => 'bio',
            '省市' => 'city',
            '转账证明' => 'certificate',
        ];

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, 1)->getValue();
                $fields[] = $val;
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : (is_object($val) ? $val->__toString() : $val);
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    // 队列异步处理
                    $insert[] = $row;
                }
            }

            /*************************************图片处理**************************************/
            if(!empty($insert)) {
                $imageFilePath = 'uploads/shop/' . date('Ymd') . '/';//图片保存目录
                create($imageFilePath);
                foreach ($currentSheet->getDrawingCollection() as $drawing) {
                    list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                    $imageFileName = md5($drawing->getPath());
                    switch ($drawing->getExtension()) {
                        case 'jpg':
                        case 'jpeg':
                            $imageFileName .= '.jpg';
                            $source = imagecreatefromjpeg($drawing->getPath());
                            if (!is_file($imageFilePath . $imageFileName)) {
                                imagejpeg($source, $imageFilePath . $imageFileName);
                            }
                            break;
                        case 'gif':
                            $imageFileName .= '.gif';
                            $source = imagecreatefromgif($drawing->getPath());
                            if (!is_file($imageFilePath . $imageFileName)) {
                                imagejpeg($source, $imageFilePath . $imageFileName);
                            }
                            break;
                        case 'png':
                            $imageFileName .= '.png';
                            $source = imagecreatefrompng($drawing->getPath());
                            if (!is_file($imageFilePath . $imageFileName)) {
                                imagejpeg($source, $imageFilePath . $imageFileName);
                            }
                            break;
                    }
                    $file_path = '/' . $imageFilePath . $imageFileName;
                    switch ($startColumn) {
                        case 'F':
                            $insert[$startRow-2]['image'] = $file_path;
                            break;
                        case 'G':
                            $insert[$startRow-2]['trademark'] = $file_path;
                            break;
                        case 'I':
                            $insert[$startRow-2]['avatar'] = $file_path;
                            break;
                        case 'L':
                            $insert[$startRow-2]['certificate'] = $file_path;
                            break;
                    }
                }
            }
            /*************************************图片处理**************************************/

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }else{
                foreach ($insert as $row) {
                    // 队列异步处理
                    Queue('app\common\job\Shop@importShop',$row,0,'gfjj');
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage(),'',$exception->getLine());
        }

        $this->success('导入成功,数据处理中...');
    }



}
